<?php

namespace app\controllers; //命名空间
use yii\web\Controller; // 导入Controller
use Yii; // 导入Yii
use app\common\Util;
use app\controllers\basecommon\BaseController;
use app\models\BlxbgameUser;


/**
* 通过code 获取用户openid
*/
class InitController extends BaseController
{

	
	public function actionGetopenid()
	{

       
            $this->judgePostMethod();//判断是否为post请求
            $grant_type = 'authorization_code';
            $postData =  Yii::$app->request->post();
            $nickName = $postData['nickname'];
            $avatarUrl = $postData['avatarUrl'];
            $JS_CODE = $postData['js_code'];
            // $nickName = 'xioaming';
            // $avatarUrl = 'https://wx.qlogo.cn/mmopen/vi_32/Kyt8uAicHLT9PXKbErL2o8xOHGAznwBvP0FwciawX2RicA7axYUEpqzBgn7z0kTIGJKIa5uPiaREKy3UEUTPb5V6Vw/0';
            // $JS_CODE = "013V4FYI1r7iM40C4p0J1vQFYI1V4FYd";
           //return json_encode( $postData);
            $APPID = YII::$app->params['WECHAT']['APPID'];
            $APPSECRET = YII::$app->params['WECHAT']['APPSECRET'];
            //将参数填写到URL
            $url_openId = YII::$app->params['URL']['OPENID'].'?appid='.$APPID.'&secret='.$APPSECRET.'&js_code='.$JS_CODE.'&grant_type='.$grant_type;

            //调用Util函数 用get请求 获取的是HTTPS请求 所以要SSL
            $util = new Util();
            $get_openid = $util->getSSL($url_openId);
            //var_dump($get_openid);
            //json格式解码
            $get_openid = json_decode($get_openid,true);

            $data = array(
                'openid' => $get_openid['openid'],
                'session_key' => $get_openid['session_key'],

            );
            //首先检查openid 在user表中是否存在
            $res =  $this->judgeOpenId($get_openid['openid']);
            //存在则直接返回到openid,不存在先保存用户openid
            if($res){
                echo json_encode( $data);
            }
            else{
                //每当用户访问时 新增数据
                $data = array(
                    'openid' => $get_openid['openid'],
                    'avatarUrl'=> $avatarUrl,
                    'nickname' => $nickName
                );
                BlxbgameUser::add($data);
            echo json_encode( $data );
            }

	}
}


?>